var oauth_fn = {
    param: {},
    qrkey: "",
    qrTime: "",
    initAuth: function () {
        let code = __zqApi.getWebURLKey("code");
        let type = __zqApi.getWebURLKey("type");
        if (code != null && type != null) {
            if (type == "gitee") {
                $.zjax({
                    type: "get",
                    url: auth_proxy,
                    zqMethod: "createGiteeUser",
                    zqParams: JSON.stringify({
                        code: code
                    }),
                    beforeSend: function () {
                        $(".model-loader").css("display", "block");
                    },
                    complete: function () {
                        $(".model-loader").css("display", "none");
                    },
                    success: function (response) {
                        let res = JSON.parse(response);
                        if (res.code == 200) {
                            Toastify({
                                text: "登录成功",
                                duration: 3000,
                                close: false,
                                style: {
                                    "color": "#ffffff"
                                },
                                gravity: "top",
                                className: "toastify-center bg-success",
                            }).showToast();
                            if (__zqApi.getWebURLKey("redirect") != null) {
                                let reurl = __zqApi.getWebURLKey("redirect");
                                if (reurl.indexOf("?zcode") != -1 || reurl.indexOf("&zcode") != -1) {
                                    __zqApi.removeQueryParam(reurl, "zcode");
                                }
                                if (reurl.indexOf("?zcode") != -1) {
                                    reurl = reurl.substr(0, reurl.lastIndexOf("?zcode"))
                                }
                                if (reurl.indexOf("?") != -1) {
                                    reurl += "&zcode=" + res.data;
                                } else {
                                    reurl += "?zcode=" + res.data;
                                }
                                window.location.replace(reurl);
                            } else {
                                window.location.replace(location_href + "?zcode=" + res.data);
                            }
                        } else {
                            Toastify({
                                text: "gitee认证登录失败，请使用其他方式登录或重试",
                                duration: 3000,
                                close: false,
                                style: {
                                    "color": "#ffffff"
                                },
                                gravity: "top",
                                className: "toastify-center bg-error",
                            }).showToast();
                        }
                    }
                })
            } else if (type == "weibo") {
                $.zjax({
                    type: "get",
                    url: auth_proxy,
                    zqMethod: "createWeiboUser",
                    zqParams: JSON.stringify({
                        code: code
                    }),
                    beforeSend: function () {
                        $(".model-loader").css("display", "block");
                    },
                    complete: function () {
                        $(".model-loader").css("display", "none");
                    },
                    success: function (response) {
                        let res = JSON.parse(response);
                        if (res.code == 200) {
                            Toastify({
                                text: "登录成功",
                                duration: 3000,
                                close: false,
                                style: {
                                    "color": "#ffffff"
                                },
                                gravity: "top",
                                className: "toastify-center bg-success",
                            }).showToast();
                            if (__zqApi.getWebURLKey("redirect") != null) {
                                let reurl = __zqApi.getWebURLKey("redirect");
                                if (reurl.indexOf("?zcode") != -1 || reurl.indexOf("&zcode") != -1) {
                                    __zqApi.removeQueryParam(reurl, "zcode");
                                }
                                if (reurl.indexOf("?zcode") != -1) {
                                    reurl = reurl.substr(0, reurl.lastIndexOf("?zcode"))
                                }
                                if (reurl.indexOf("?") != -1) {
                                    reurl += "&zcode=" + res.data;
                                } else {
                                    reurl += "?zcode=" + res.data;
                                }
                                window.location.replace(reurl);
                            } else {
                                window.location.replace(location_href + "?zcode=" + res.data);
                            }
                        } else {
                            Toastify({
                                text: "微博认证登录失败，请使用其他方式登录或重试",
                                duration: 3000,
                                close: false,
                                style: {
                                    "color": "#ffffff"
                                },
                                gravity: "top",
                                className: "toastify-center bg-error",
                            }).showToast();
                        }
                    }
                })
            }
        }
    },

    /**
     * 初始化cookie
     */
    initCookie: function () {
        let phone = $.cookie(phone_key);
        if (phone && phone != "null") {
            $(".form-input-mobile").val(phone);
            $(".form-checkbox-remember-mobile").prop("checked", true);
        }
    },

    /**
     * 初始化事件
     */
    initEvent: function () {
        $(".btn-login-send-message").click(function () {
            let phone = $(".form-input-mobile").val();
            if (!new RegExp(/^[1][345678][0-9]{9}$/).test(phone)) {
                Toastify({
                    text: "手机号格式不正确！",
                    duration: 3000,
                    close: false,
                    style: {
                        "color": "#ffffff"
                    },
                    gravity: "top",
                    className: "toastify-center bg-error",
                }).showToast();
                $(".form-input-mobile").focus();
                return;
            }
            $(".btn-base-modal").click();
            oauth_fn.param = {
                type: 0,
                phone: phone,
                code: null,
                isR: null
            }
        })
        $(".btn-login").click(function () {
            let phone = $(".form-input-mobile").val();
            if (!new RegExp(/^[1][3456789][0-9]{9}$/).test(phone)) {
                Toastify({
                    text: "手机号格式不正确！",
                    duration: 3000,
                    close: false,
                    style: {
                        "color": "#ffffff"
                    },
                    gravity: "top",
                    className: "toastify-center bg-error",
                }).showToast();
                $(".form-input-mobile").focus();
                return;
            }
            let code = $(".form-input-code").val();
            if (!new RegExp(/^[-]{0,1}[0-9]{6}$/).test(code)) {
                Toastify({
                    text: "验证码格式不正确！",
                    duration: 3000,
                    close: false,
                    style: {
                        "color": "#ffffff"
                    },
                    gravity: "top",
                    className: "toastify-center bg-error",
                }).showToast();
                $(".form-input-code").focus();
                return;
            }
            let isR = $(".form-checkbox-remember-mobile").prop("checked");
            $(".btn-base-modal").click();
            oauth_fn.param = {
                type: 1,
                phone: phone,
                code: code,
                isR: isR
            }
        })
    },

    /**
     * 初始化插件
     */
    initPlugin: function () {
        oauth_fn.initSlider();
    },

    initSlider: function () {
        $('#captcha').sliderCaptcha({
            repeatIcon: 'fa fa-redo',
            setSrc: function () {
                return 'static/image/ver-' + Math.round((Math.random() * 2) + 1) + '.png';
            },
            onSuccess: function () {
                $(".btn-slider-captcha-modal-close").click();
                if (oauth_fn.param.type == 0) {
                    $.zjax({
                        type: "post",
                        url: `${auth_proxy}`,
                        zqMethod: "sendMobileCode",
                        zqParams: JSON.stringify({
                            "phone": oauth_fn.param.phone
                        }),
                        success: function (response) {
                            let res = JSON.parse(response);
                            if (res.code == 200) {
                                Toastify({
                                    text: "短信已发送，请留意手机，60秒后可重新发送。",
                                    duration: 3000,
                                    close: false,
                                    style: {
                                        "color": "#ffffff"
                                    },
                                    className: "toastify-center bg-info",
                                    gravity: "top"
                                }).showToast();
                                let ct = 60;
                                $(".btn-login-send-message").addClass("disabled:pointer-events-none disabled:select-none disabled:opacity-60")
                                    .prop('disabled', true);
                                let t1 = window.setInterval(function () {
                                    $(".btn-login-send-message").text(ct + "s后重发");
                                    ct--;
                                    if (ct == 0) {
                                        $(".btn-login-send-message").removeClass("disabled:pointer-events-none disabled:select-none disabled:opacity-60")
                                            .text("发送短信").prop('disabled', false);
                                        clearInterval(t1);
                                    }
                                }, 1000);
                            } else {
                                Toastify({
                                    text: res.msg,
                                    duration: 3000,
                                    close: false,
                                    style: {
                                        "color": "#ffffff"
                                    },
                                    gravity: "top",
                                    className: "toastify-center bg-error",
                                }).showToast();
                                // 短信服务停用
                                if (res.code == 5050) {
                                    let code = res.msg.substr(res.msg.indexOf(" ") + 1, 6);
                                    $(".form-input-code").val(code);
                                }
                            }
                        }
                    })
                } else if (oauth_fn.param.type == 1) {
                    let data = {
                        mobile: oauth_fn.param.phone,
                        code: oauth_fn.param.code
                    }
                    $.zjax({
                        url: `${auth_proxy}`,
                        type: "POST",
                        zqMethod: "login",
                        zqParams: JSON.stringify({
                            mobileLoginDto: data
                        }),
                        // xhrFields:{
                        //     withCredentials:true
                        // },
                        contentType: "application/json",
                        success: function (response) {
                            let res = JSON.parse(response);
                            if (res.code == 200) {
                                if (oauth_fn.param.isR) {
                                    $.cookie(phone_key, oauth_fn.param.phone, {expires: 7, path: "/"});
                                } else {
                                    $.cookie(phone_key, null);
                                }
                                Toastify({
                                    text: "登录成功",
                                    duration: 3000,
                                    close: false,
                                    style: {
                                        "color": "#ffffff"
                                    },
                                    gravity: "top",
                                    className: "toastify-center bg-success",
                                }).showToast();
                                if (__zqApi.getWebURLKey("redirect") != null) {
                                    let reurl = __zqApi.getWebURLKey("redirect");
                                    if (reurl.indexOf("?zcode") != -1 || reurl.indexOf("&zcode") != -1) {
                                        __zqApi.removeQueryParam(reurl, "zcode");
                                    }
                                    if (reurl.indexOf("?zcode") != -1) {
                                        reurl = reurl.substr(0, reurl.lastIndexOf("?zcode"))
                                    }
                                    if (reurl.indexOf("?") != -1) {
                                        reurl += "&zcode=" + res.data;
                                    } else {
                                        reurl += "?zcode=" + res.data;
                                    }
                                    window.location.replace(reurl);
                                } else {
                                    window.location.replace(location_href + "?zcode=" + res.data);
                                }
                            } else {
                                Toastify({
                                    text: res.msg,
                                    duration: 3000,
                                    close: false,
                                    style: {
                                        "color": "#ffffff"
                                    },
                                    gravity: "top",
                                    className: "toastify-center bg-error",
                                }).showToast();
                            }
                        },
                        error: function () {

                        },
                        complete: function () {
                            //$(".btn-slider-captcha-modal-close").click();
                        }
                    });
                }

            },
            onFail: function () {

            }
        });
    },

    initWyy: function () {
        $(".btn-wyy-login").click(function () {
            oauth_fn.loadQr();
        })
    },

    loadQr: function () {
        $.get(`${wyy_server}/login/qr/key?timerstamp=${Date.now()}`, function (response) {
            if (response && response.code == 200 && response.data.code == 200) {
                oauth_fn.qrkey = response.data.unikey;
                $.get(`${wyy_server}/login/qr/create?key=${oauth_fn.qrkey}&qrimg=true&timerstamp=${Date.now()}`, function (responseQr) {
                    if (responseQr.code == 200) {
                        let qrimg = responseQr.data.qrimg;
                        $(".qr_img").attr("src", qrimg);
                        oauth_fn.checkQr();
                    }
                })
            }
        })
    },

    checkQr: function () {
        if (oauth_fn.qrTime) {
            clearInterval(oauth_fn.qrTime);
        }
        oauth_fn.qrTime = setInterval(function () {
            $.get(`${wyy_server}/login/qr/check?key=${oauth_fn.qrkey}&timerstamp=${Date.now()}`, function (response) {
                //801等待扫描
                if (response.code === 800) {
                    oauth_fn.loadQr();
                }
                if (response.code === 803) {
                    oauth_fn.checkState2(response);
                    // 这一步会返回cookie
                    $("#waitGetState").click();
                    clearInterval(oauth_fn.qrTime);
                    localStorage.setItem('wyy_cookie', response.cookie);
                }
            })
        }, 3000);
    },

    checkState2: function (response) {
        $.ajax({
            url: `${wyy_server}/login/status?timerstamp=${Date.now()}`,
            type: "post",
            data: {
                cookie: response.cookie
            },
            beforeSend: function () {
                Toastify({
                    text: "授权登录成功，正在检查登录状态...",
                    duration: 3000,
                    close: false,
                    style: {
                        "color": "#ffffff"
                    },
                    gravity: "top",
                    className: "toastify-center bg-success",
                }).showToast();
            },
            success: function (response) {
                if (response.data.account.status >= 0) {
                    localStorage.setItem('wyy_id', response.data.account.id);
                    setTimeout(function () {
                        Toastify({
                            text: "检查登录状态完成，即将登录...",
                            duration: 3000,
                            close: false,
                            style: {
                                "color": "#ffffff"
                            },
                            gravity: "top",
                            className: "toastify-center bg-success",
                        }).showToast();
                        $.zjax({
                            url: `${auth_proxy}`,
                            type: "POST",
                            zqMethod: "loginByWyy",
                            zqParams: JSON.stringify({
                                "wyy": JSON.stringify(response.data.profile)
                            }),
                            contentType: "application/json",
                            success: function (response) {
                                let res = JSON.parse(response);
                                if (res.code == 200) {
                                    Toastify({
                                        text: "登录成功",
                                        duration: 3000,
                                        close: false,
                                        style: {
                                            "color": "#ffffff"
                                        },
                                        gravity: "top",
                                        className: "toastify-center bg-success",
                                    }).showToast();
                                    if (__zqApi.getWebURLKey("redirect") != null) {
                                        let reurl = __zqApi.getWebURLKey("redirect");
                                        if (reurl.indexOf("?zcode") != -1 || reurl.indexOf("&zcode") != -1) {
                                            __zqApi.removeQueryParam(reurl, "zcode");
                                        }
                                        if (reurl.indexOf("?zcode") != -1) {
                                            reurl = reurl.substr(0, reurl.lastIndexOf("?zcode"))
                                        }
                                        if (reurl.indexOf("?") != -1) {
                                            reurl += "&zcode=" + res.data;
                                        } else {
                                            reurl += "?zcode=" + res.data;
                                        }
                                        window.location.replace(reurl);
                                    } else {
                                        window.location.replace(location_href + "?zcode=" + res.data);
                                    }
                                } else {
                                    Toastify({
                                        text: res.msg,
                                        duration: 3000,
                                        close: false,
                                        style: {
                                            "color": "#ffffff"
                                        },
                                        gravity: "top",
                                        className: "toastify-center bg-error",
                                    }).showToast();
                                }
                            },
                            error: function () {

                            },
                            complete: function () {
                                //$(".btn-slider-captcha-modal-close").click();
                            }
                        });
                    }, 2000)
                } else {
                    Toastify({
                        text: "检查登录状态异常，请用其他方式登录",
                        duration: 3000,
                        close: false,
                        style: {
                            "color": "#ffffff"
                        },
                        gravity: "top",
                        className: "toastify-center bg-error",
                    }).showToast();
                }
            },
            error: function () {
                Toastify({
                    text: "检查登录状态异常，请用其他方式登录",
                    duration: 3000,
                    close: false,
                    style: {
                        "color": "#ffffff"
                    },
                    gravity: "top",
                    className: "toastify-center bg-error",
                }).showToast();
            }
        })
    }
}